import { Injectable } from "@nestjs/common";
import { appConfig } from "src/app.config";
import business from "src/common/business";
import response from "src/common/response";
import { User } from "src/entities/sql/user.entity";
import { UserToken } from "src/entities/user.token";
import { Connection, Repository } from "typeorm";

@Injectable()
export class UserService {
    usersRepository: Repository<User>;

    constructor(connection: Connection) {
        this.usersRepository = connection.getRepository(User);
    }

    async doLogin(mobileNo: string, password: string) {
        let _user = await this.usersRepository.findOne({
            mobileNo: mobileNo,
            password: business.md5(password)
        });
        if (!_user) {
            return response.error("用户名或密码不正确");
        }
        let userToken: UserToken = {
            userId: _user.id,
            userName: _user.userName,
            expireTime: business.getNowAfterDay(appConfig.userExpiryTime)
        }
        return response.okData(business.jwtEncrypt(userToken));
    }
}